package org.example.netty.test.nio.netty.chat.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.example.netty.test.nio.netty.chat.bean.RpcRequest;
import org.example.netty.test.nio.netty.chat.bean.RpcResponse;
import org.example.netty.test.nio.netty.chat.service.UserService;
import org.example.netty.test.nio.util.ServiceFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zp
 * @version 1.0
 * @description: RPC请求消息处理器
 * @date 2023/5/31 18:39
 */
@Slf4j
public class RpcRequestHandler extends SimpleChannelInboundHandler<RpcRequest> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequest msg) {
        String requestId = msg.getRequestId();
        Object[] parameters = msg.getParameters();
        Class<?>[] parameterTypes = msg.getParameterTypes();
        String className = msg.getClassName();
        String methodName = msg.getMethodName();
        UserService service;
        RpcResponse rpcResponse = new RpcResponse();

        rpcResponse.setRequestId(requestId);
        Map<String, Object> params = new HashMap<>();
        params.put("message", "success");
        params.put("code", "0000");
        rpcResponse.setResult(params);
        try {
            Class<?> c = Class.forName(className);
            service = (UserService) ServiceFactory.buildService(c);
            Method method = service.getClass().getMethod(methodName, parameterTypes);
            method.invoke(service, parameters);
        } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException |
                 ClassNotFoundException e) {
            log.error("异常信息：{}", e.getMessage());
            params.clear();
            params.put("message", "fail");
            params.put("code", "9999");
            rpcResponse.setResult(params);
            rpcResponse.setError(e.getMessage());
        }
        ctx.channel().writeAndFlush(rpcResponse);
    }
}
